<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index()
    {
        $products = Product::latest()->paginate(10);
        return view('home-components.product-list', compact('products'));
    }

    public function create()
    {
        return view('home-components.product-create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'stock' => 'required|integer|min:0',
            'status' => 'required|in:0,1',
            'main_image' => 'nullable|image|max:2048',
            'images' => 'nullable|array',
            'images.*' => 'image|max:2048'
        ]);

        $product = Product::create($validated);

        if ($request->hasFile('main_image')) {
            $product->main_image = $request->file('main_image')->store('products', 'public');
            $product->save();
        }

        if ($request->hasFile('images')) {
            $images = [];
            foreach ($request->file('images') as $image) {
                $images[] = $image->store('products', 'public');
            }
            $product->images = $images;
            $product->save();
        }

        return redirect()->route('products.index')->with('success', '商品添加成功！');
    }

    public function edit(Product $product)
    {
        return view('home-components.product-edit', compact('product'));
    }

    public function update(Request $request, Product $product)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'stock' => 'required|integer|min:0',
            'status' => 'required|in:0,1',
            'main_image' => 'nullable|image|max:2048',
            'images' => 'nullable|array',
            'images.*' => 'image|max:2048'
        ]);

        $product->update($validated);

        if ($request->hasFile('main_image')) {
            $product->main_image = $request->file('main_image')->store('products', 'public');
            $product->save();
        }

        if ($request->hasFile('images')) {
            $images = [];
            foreach ($request->file('images') as $image) {
                $images[] = $image->store('products', 'public');
            }
            $product->images = $images;
            $product->save();
        }

        return redirect()->route('products.index')->with('success', '商品更新成功！');
    }

    public function destroy(Product $product)
    {
        $product->delete();
        return redirect()->route('products.index')->with('success', '商品删除成功！');
    }
} 